package com.newflypig.jblog.util;

import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.TimeZone;

import com.newflypig.jblog.model.Article;
import com.newflypig.jblog.model.ArticleDateMap;
import com.newflypig.jblog.model.BlogCommon;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

public class FreemarkerUtil {
	
	public void generateRSS(List<Article> articleList,BlogCommon blogCommon, String templateFilePath, String outputFilePath) throws IOException, TemplateException{
		Configuration cfg = new Configuration(Configuration.VERSION_2_3_23);
		cfg.setDirectoryForTemplateLoading(new File(templateFilePath));
		cfg.setDefaultEncoding("UTF-8");
		cfg.setClassicCompatible(true);
		cfg.setLocale(Locale.ENGLISH);
		cfg.setTimeZone(TimeZone.getTimeZone("GMT"));
		cfg.setDateTimeFormat("EEE, d MMM yyyy hh:mm:ss z");
		
		Map<String, Object> root = new HashMap<String, Object>();
		root.put("articleList", articleList);
		root.put("blogCommon", blogCommon);
		root.put("today", new Date());
		
		Template temp = cfg.getTemplate("rss.xml");
		
		File outFile = new File(outputFilePath);
		FileOutputStream fos = new FileOutputStream(outFile);
        Writer out = new BufferedWriter(new OutputStreamWriter(fos,"utf-8"));                               
		
		temp.process(root, out);
		
		out.close();
		fos.close();
	}
	
	public String generateSingleAriticleListHtml(List<ArticleDateMap> admList, String templateFilePath) throws IOException, TemplateException{
		Configuration cfg = new Configuration(Configuration.VERSION_2_3_23);
		cfg.setDirectoryForTemplateLoading(new File(templateFilePath));
		cfg.setDefaultEncoding("UTF-8");
		cfg.setClassicCompatible(true);
		
		Map<String, Object> root = new HashMap<String, Object>();
		root.put("admList", admList);
		
		Template temp = cfg.getTemplate("article/singleArticle.html");
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		Writer out = new BufferedWriter(new OutputStreamWriter(baos, "utf-8"));
		
		temp.process(root, out);
		
		out.close();
		return baos.toString("utf-8");
	}
}
